﻿using System;
using System.Collections.Generic;
using System.Text;
using agsXMPP.protocol.client;
using agsXMPP;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;

namespace GtalkBot
{
    class Gbot
    {
        agsXMPP.XmppClientConnection objXmpp;
        public string alFriendsList = "";
        public string Status;
        INIClass config = new INIClass(Application.StartupPath + "/config.ini");
        WinIO32 IO = new WinIO32();



        public Gbot(string username, string password)
        {

            objXmpp = new agsXMPP.XmppClientConnection();
            agsXMPP.Jid jid = null;
            jid = new agsXMPP.Jid(username.Split('@').Length == 1 ? username + "@gmail.com" : username);
            objXmpp.Password = password;
            objXmpp.Username = jid.User;
            objXmpp.Server = jid.Server;
            objXmpp.AutoResolveConnectServer = true;

            try
            {
                objXmpp.OnMessage += messageReceived;
                objXmpp.OnAuthError += loginFailed;
                objXmpp.OnLogin += loggedIn;
                objXmpp.OnPresence += Presence;
                objXmpp.Open();
                Status = "正在登录";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void loginFailed(object o, agsXMPP.Xml.Dom.Element el)  //登录失败
        {
            Status = "登录失败";
        }

        private void loggedIn(object sender) //登录成功
        {
            Status = "登录成功";
        }

        private void Presence(object ender, agsXMPP.protocol.client.Presence pres)  //状态处理
        {
            //****************处理好友请求************************//   
            string sts = pres.ToString();
            if (pres.Type == agsXMPP.protocol.client.PresenceType.subscribe)
            {
                //提问用户是否接受好友请求    
                //收到好友请求

                sts = "subscribe 收到好友请求" + pres.From.ToString();
                if (config.IniReadValue("LoginInfo", "autofriend") == "true")
                {
                    agsXMPP.protocol.client.PresenceManager presenceManager = new PresenceManager(objXmpp);
                    presenceManager.Subscribe(new Jid(pres.From.ToString()));

                }






            }
            else if (pres.Type == PresenceType.subscribed)
            {
                sts = " PresenceType.subscribed";
            }
            else if (pres.Type == PresenceType.unsubscribe)
            {

            }
            else if (pres.Type == PresenceType.unsubscribed)
            {
                //收到“拒绝请求”或者“被T”的时候    
            }
            else
            {
                //处理好友上线/离线的事件处理    
                if (pres.From.Bare.Equals(objXmpp.MyJID.Bare) == false)
                {
                    //如果不是自己的信息，即好友信息    
                    //检测该好友是否不存在于好友列表(OnPresence比OnRosterItem优先处理添加好友)，则自动添加ListItem    
                    //添加到好友列表  

                    if (alFriendsList.IndexOf(pres.From.Bare) == -1)
                    {
                        alFriendsList += "⊹" + pres.From.ToString();

                    }
                    sts = "'判断该好友目前的状态，上线还是离线    " + pres.Show;
                    if (pres.Type == PresenceType.available && pres.Show == ShowType.NONE)
                    {
                        sts = "在线";
                        //莫名其妙
                    }
                    else if (pres.Type == PresenceType.available && pres.Show == ShowType.chat)
                    {
                        sts = "  '如果好友上线，并且是chat状态  ";
                    }
                    else if (pres.Type == PresenceType.available && pres.Show == ShowType.away)
                    {
                        sts = " '如果好友上线，并且是away状态  ";
                    }
                    else if (pres.Type == PresenceType.unavailable)
                    {
                        sts = " '如果好友离线    ";
                    }
                }
            }
        }


        private void messageReceived(object sender, agsXMPP.protocol.client.Message msg) // 接收消息
        {
            string msgstr = msg.Body;
            string outmsg = "";
            string cmdhead = msgstr.Substring(0, 1);
            string cmd = msgstr.Substring(1);


            switch (cmdhead)
            {
                case "#":
                    try
                    {
                        if (config.IniReadValue("LoginInfo", "opencmd") == "true")
                        {
                            outmsg = CMD_sh._CMD(cmd, msg);
                        }
                        else
                        {
                            outmsg = "错误:没有开启这个功能";
                        }


                    }
                    catch (Exception ex)
                    {

                        outmsg = "错误:" + ex.ToString();
                    }
                    break;
                case "%":
                    try
                    {
                        if (config.IniReadValue("LoginInfo", "AC") == "true")
                        {
                            string str = Tools.getac(cmd);
                            JSONObject json = JSONConvert.DeserializeObject(str);
                            if (json != null)
                            {
                                outmsg += "账号状态：" + json["status"].ToString() + "\n";
                                int i = 0;
                                while (i < ((JSONArray)json["data"]).Count)
                                {
                                    outmsg += Tools.AtoS(((JSONObject)((JSONArray)json["data"])[i])["website"].ToString()) + "   " + ((JSONObject)((JSONArray)json["data"])[i])["username"].ToString() + "   " + ((JSONObject)((JSONArray)json["data"])[i])["email"].ToString() + "\n";
                                    i++;
                                }

                            }

                            outmsg += "数据来自：lucky.anquanbao.com";
                        }
                        else
                        {
                            outmsg = "错误:没有开启这个功能";
                        }


                    }
                    catch (Exception ex)
                    {

                        outmsg = "错误:" + ex.ToString();
                    }
                    break;
                case "@":
                    try
                    {
                        if (config.IniReadValue("LoginInfo", "openkey") == "true")
                        {
                            if (cmd == "n")
                            {
                                IO.KeyDown(WinIO32.Keys.VK_CONTROL);
                                IO.KeyDownUp(WinIO32.Keys.VK_RIGHT);
                                Thread.Sleep(100);
                                IO.KeyUp(WinIO32.Keys.VK_CONTROL);

                                outmsg = "下一首";
                            }
                            else if (cmd == "p")
                            {
                                IO.KeyDown(WinIO32.Keys.VK_CONTROL);
                                IO.KeyDownUp(WinIO32.Keys.VK_LEFT);
                                Thread.Sleep(100);
                                IO.KeyUp(WinIO32.Keys.VK_CONTROL);

                                outmsg = "上一首";
                            }

                            outmsg += " 发送成功";



                        }
                        else
                        {
                            outmsg = "错误:没有开启这个功能";
                        }


                    }
                    catch (Exception ex)
                    {

                        outmsg = "错误:" + ex.ToString();
                    }
                    break;
                case "$":
                    try
                    {
                        if (config.IniReadValue("LoginInfo", "sqlchk") == "true")
                        {
                            SqlConnection cn = new SqlConnection(config.IniReadValue("SQL", "sqlcon"));
                            string a = "insert into GSpeak (ask,ans) values ('" + cmd.Split('^')[0] + "','" + cmd.Split('^')[1] + "')";
                            SqlCommand cm = new SqlCommand(a, cn);
                            cn.Open();
                            cm.ExecuteNonQuery();
                            cn.Close();
                            outmsg = "我学会了";
                        }
                        else
                        {
                            config.IniWriteValue("message", cmd.Split('^')[0], cmd.Split('^')[1]);
                            outmsg = "我学会了";
                        }




                    }
                    catch
                    {
                        outmsg = "错误691";
                    }


                    break;
                case "?":
                    outmsg = "输入 # 加命令 来执行 如 #ipconfig \n 输入$问题^答案  来教会机器人说话";
                    break;
                default:
                    try
                    {
                        if (config.IniReadValue("LoginInfo", "sqlchk") == "true")
                        {
                            SqlConnection cn = new SqlConnection(config.IniReadValue("SQL", "sqlcon"));
                            string a = "select ans  from  GSpeak where   ask like '%" + msgstr + "%' or '" + msgstr + "' like '%'+ask+'%' order by id desc";
                            SqlCommand cm = new SqlCommand(a, cn);
                            SqlDataReader rs;
                            cn.Open();
                            rs = cm.ExecuteReader();
                            if (rs.Read())
                            {
                                outmsg = rs[0].ToString();
                            }

                            cn.Close();
                        }
                        else
                        {
                            outmsg = config.IniReadValue("message", msgstr);
                        }

                    }
                    catch (Exception)
                    {
                        outmsg = "错误692";
                    }


                    if (outmsg == "")
                        outmsg = "无法识别命令:" + msgstr + "\n" + "输入 ? 来获取帮助";


                    // outmsg = "select ans  from  GSpeak where   ask like '%" + msgstr + "%' or '" + msgstr + "' like '%'+ask+'%'  )";

                    break;
            }

            string[] chatMessage = null;
            chatMessage = msg.From.ToString().Split('/');
            agsXMPP.Jid jid = default(agsXMPP.Jid);
            jid = new agsXMPP.Jid(chatMessage[0]);
            agsXMPP.protocol.client.Message autoReply = default(agsXMPP.protocol.client.Message);
            autoReply = new agsXMPP.protocol.client.Message(jid, agsXMPP.protocol.client.MessageType.chat, outmsg);
            objXmpp.Send(autoReply);
        }





    }
}
